﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisHelp
{
    public class RedisLock : IDisposable
    {
        private readonly IDatabase _db = null;
        private readonly string key;
        private readonly RedisValue token;
        public RedisLock(IDatabase redisClient, string _key, TimeSpan? timeOut = null)
        {
            _db = redisClient;
            key = _key;
            token = Environment.MachineName;
            var _timeOut = (timeOut == null ? TimeSpan.FromSeconds(20) : timeOut.Value).Add(TimeSpan.FromMilliseconds(100));
            ExecUtils.RetryUntilTrue(() =>
            {
                var firstAttempt = DateTime.UtcNow;
                var __timeOut = (timeOut == null ? TimeSpan.FromSeconds(20) : timeOut.Value);
                return _db.LockTake(key, token, __timeOut);
            }, _timeOut);
        }

        public void Dispose()
        {
            _db.LockRelease(key, token);
        }
    }
}
